﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http;
using System.Collections.Concurrent;
using System.IO;
using System.Net.Http;
using System.Net;

namespace ERPStore.Host
{
	public class PushLogController : ApiController
	{
		private static ERPStore.Services.PushSubscriberService PushSubscriberService
			= new Services.PushSubscriberService();

		public HttpResponseMessage GetUpdates(HttpRequestMessage request)
		{
			var apiKeyHeader = request.Headers.FirstOrDefault(h => "apikey".Equals(h.Key, StringComparison.InvariantCultureIgnoreCase));
			if (apiKeyHeader.Value == null)
			{
				var httpMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				throw new HttpResponseException(httpMessage);
			}
			if (!apiKeyHeader.Value.First().Equals(ERPStore.GlobalConfiguration.Configuration.Settings.ApiToken))
			{
				var httpMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				throw new HttpResponseException(httpMessage);
			}

			var clientId = Guid.NewGuid().ToString();

			var clientNameHeader = request.Headers.FirstOrDefault(h => "ClientName".Equals(h.Key, StringComparison.InvariantCultureIgnoreCase));
			var clientName = string.Empty;
			if (clientNameHeader.Value != null)
			{
				clientName = clientNameHeader.Value.First();
			}

			request.Headers.Clear();
			var response = request.CreateResponse();
			response.Content = new PushStreamContent((stream, content, context) =>
				{
					var subscriber = new ERPStore.Models.PushSubscriber()
					{
						ClientName = clientName,
						StreamWriter = new StreamWriter(stream)
					};

					PushSubscriberService.Add(subscriber);
				}
				, "text/plain");
			return response;
		}

		public static void WriteMessage(string message)
		{
			PushSubscriberService.WriteMessage(message);
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			PushSubscriberService.Dispose();
		}
	}
}
